package com.lc.filter;

import com.lc.bean.Emp;
import com.lc.utils.Constants;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class LoginFilter implements Filter {

    List<String> allowUris = new ArrayList<>();

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        allowUris.add("/login.jsp");
        allowUris.add("/favicon.ico");
        allowUris.add("/emp/login");
        allowUris.add("/");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//        System.out.println("我是过滤器..........guolvqi");
        // 1、获取请求的资源路径
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        String url = req.getRequestURI();


        // 2、放行一部分（不用登陆就可以访问的，登陆界面/login.jsp，登陆接口/emp/login）
        if(allowUris.contains(url)
                || url.contains("/plugins")
             || url.contains("/.well-known")) {
            System.out.println("fangxing------" + url);
            filterChain.doFilter(req,servletResponse);
            return;
        }
        System.out.println("lanjie："+ url);
        // 3、其他资源必须要登陆
        Emp loginEmp = (Emp) req.getSession().getAttribute(Constants.LOGIN_USER_TAG);
        if(loginEmp != null) {
            filterChain.doFilter(req,servletResponse);
            return;
        }

        // 京东会记住这个地址，作为一个参数传递给登陆界面，登陆完成，自动跳回来 /order/approveList
        String redirectUrl = req.getScheme() +"://localhost:"+req.getServerPort()+ url;

        // 跳转到登陆界面
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        // http://localhost:8080/login.jsp?redirectUrl=http://localhost:8080/order/approveList
        resp.sendRedirect("/login.jsp?redirectUrl="+redirectUrl );
    }

    @Override
    public void destroy() {

    }
}
